//
//  UWFriendManager.m
//  Urban Words
//
//  Created by Tim Brandin on 2011-11-21.
//  Copyright (c) 2011 Sypreme. All rights reserved.
//

#import "UWFriendManager.h"
#import "UWApi.h"
#import "UWAppDelegate.h"

static UWFriendManager *shared = nil;

@implementation UWFriendManager

@synthesize facebook, count, sections;
@synthesize delegate;

- (id)init
{
    self = [super init];
    if (self) {
        
        delegates = [[NSMutableArray alloc] init];
        
        NSArray *dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        NSString *docsDir = [dirPath objectAtIndex:0];
        
        dbPath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:@"friends.db"]];
        
        NSFileManager *filemgr = [NSFileManager defaultManager];
        
        if ([filemgr fileExistsAtPath:dbPath] == NO) {
            const char *dbpath = [dbPath UTF8String];
            
            if (sqlite3_open(dbpath, &friendsDB) == SQLITE_OK) {
                char *errMsg;
                const char *sql_stmt = "CREATE TABLE IF NOT EXISTS friends (id VARCHAR(30) PRIMARY KEY, name TEXT, first_name VARCHAR(100), sex VARCHAR(10), gameswon VARCHAR(7), gamehighscore VARCHAR(4), wordhighscore VARCHAR(4))";
                
                if (sqlite3_exec(friendsDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) {
                    NSLog(@"Failed to create table");
                }
                
                sqlite3_close(friendsDB);
            }
            else {
                NSLog(@"Failed to open/create database");
            }
            
        }
        
        if (!facebook) {
        
            UWAppDelegate *appDelegate = (UWAppDelegate *)[[UIApplication sharedApplication] delegate];
        
            facebook = appDelegate.facebook;
        }
        
        [filemgr release];
        
    }
    
    return self;
}

- (void)updateFriends 
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"FBAccessTokenKey"] 
        && [defaults objectForKey:@"FBExpirationDateKey"]) {

        NSLog(@"UPDATE FRIENDS: %fs", [lastUpdated timeIntervalSinceNow]);
        
        if (lastUpdated == nil || [lastUpdated timeIntervalSinceNow] < -300) {
            
            if ([self count] > 0) {
                return;
            }
        
            lastUpdated = [[NSDate alloc] init];
        
            NSLog(@"%@", lastUpdated);
        
            NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
            [dict setValue:[facebook accessToken] forKey:@"access_token"];
            [facebook requestWithGraphPath:@"fql?q=SELECT+uid,name,first_name,sex+FROM+user+WHERE+uid+IN+(SELECT+uid2+FROM+friend+WHERE+uid1=me())" andParams:[dict autorelease] andDelegate:self];
        }
    }
}

- (void)downloadImage:(UWFriend *)person 
{
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *pngFilePath = [NSString stringWithFormat:@"%@/%@.png", docDir, person.fid];
    
    BOOL retina = [[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2.0;
    
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%@/picture%@", person.fid, retina?@"?type=normal":@""]]]];
    
    if (retina) {
        CGSize size = [image size];
        CGRect cropRect;
        if (size.height > 100) {
            cropRect = CGRectMake(0, 0, 100, 100);
        } else {
            cropRect = CGRectMake((int)((size.width - size.height)/2.f), 0, size.height, size.height);
        }
        
        CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);
        UIImage *newImage = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:image.imageOrientation];
        image = newImage;
        
        CGImageRelease(imageRef);
    }
    
    NSData *data = [NSData dataWithData:UIImagePNGRepresentation(image)];
    [data writeToFile:pngFilePath atomically:YES];
    
    // if indexPath is still in table, update the cell with an image
    if (person.indexPath && person.table) {
        if ([[person.table indexPathsForVisibleRows] containsObject:person.indexPath]) {
            UITableViewCell *cell = [person.table cellForRowAtIndexPath:person.indexPath];
            if (cell != nil) {
                cell.imageView.image = image;
                [cell setNeedsLayout];
            }
        }
    }
}

- (void)downloadLargeImage:(UWFriend *)person 
{
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *pngFilePath = [NSString stringWithFormat:@"%@/%@-large.png", docDir, person.fid];
    
    BOOL retina = [[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2.0;
    
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%@/picture%@", person.fid, retina?@"?type=large":@"?type=normal"]]]];
    
    CGSize size = [image size];
    CGRect cropRect;
    
    if (retina) {
        if (size.height > 200) {
            cropRect = CGRectMake(0, 0, 200, 200);
        } else {
            cropRect = CGRectMake((int)((size.width - size.height)/2.f), 0, size.height, size.height);
        }
    } else {
        if (size.height > 100) {
            cropRect = CGRectMake(0, 0, 100, 100);
        } else {
            cropRect = CGRectMake((int)((size.width - size.height)/2.f), 0, size.height, size.height);
        }
    }
    
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);
    UIImage *newImage = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:image.imageOrientation];
    image = newImage;
    
    CGImageRelease(imageRef);
    
    NSData *data = [NSData dataWithData:UIImagePNGRepresentation(image)];
    [data writeToFile:pngFilePath atomically:YES];
    
    // if indexPath is still in table, update the cell with an image
    if (person.indexPath && person.table) {
        if ([[person.table indexPathsForVisibleRows] containsObject:person.indexPath]) {
            UITableViewCell *cell = [person.table cellForRowAtIndexPath:person.indexPath];
            if (cell != nil) {
                cell.imageView.image = image;
                [cell setNeedsLayout];
            }
        }
    }
}

- (UIImage *)getLargeImage:(UWFriend *)person 
{
    BOOL retina = [[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2.0;
    
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%@/picture%@", person.fid, retina?@"?type=large":@"?type=normal"]]]];
    
    CGSize size = [image size];
    CGRect cropRect;
    
    if (retina) {
        if (size.height > 200) {
            cropRect = CGRectMake(0, 0, 200, 200);
        } else {
            cropRect = CGRectMake((int)((size.width - size.height)/2.f), 0, size.height, size.height);
        }
    } else {
        if (size.height > 100) {
            cropRect = CGRectMake(0, 0, 100, 100);
        } else {
            cropRect = CGRectMake((int)((size.width - size.height)/2.f), 0, size.height, size.height);
        }
    }
    
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);
    UIImage *newImage = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:image.imageOrientation];
    return newImage;
}

// Singleton

+ (UWFriendManager *)sharedManager 
{
    if (shared == nil) {
        // allocate the shared istance, because it hasn't been done yet
        shared = [[super allocWithZone:NULL] init];
    }
    return shared;
}

+ (id)allocWithZone:(NSZone *)zone 
{
    return [[self sharedManager] retain];
}

- (id)copyWithZone:(NSZone *)zone 
{
    return self;
}

- (id)retain 
{
    return self;
}

- (NSUInteger)retainCount 
{
    return NSUIntegerMax;
}

- (oneway void)release 
{
    // Do nothing
}

- (id)autorelease 
{
    return self;
}

// End of singleton

// Facebook

- (void)requestLoading:(FBRequest *)request 
{
    NSLog(@"Loading");
}

- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response 
{
    //NSLog(@"Response %@", response);
}

- (void)request:(FBRequest *)request didFailWithError:(NSError *)error 
{
    //NSLog(@"Fail: %@", error);
}

- (void)request:(FBRequest *)request didLoad:(id)result 
{
    
    int before = self.count;
    
    sqlite3_stmt *statement;
    
    const char *dbpath = [dbPath UTF8String];
    
    if (sqlite3_open(dbpath, &friendsDB) == SQLITE_OK) {
    
        NSArray *data = [[(NSDictionary *)result objectForKey:@"data"] retain];
        
        for (NSObject *o in data) {
            NSString *insertSQL = [NSString stringWithFormat:@"INSERT OR REPLACE INTO friends (id, name, first_name, sex, gameswon, gamehighscore, wordhighscore) VALUES (\"%@\", \"%@\", \"%@\", \"%@\", \"%i\", \"%i\", \"%i\")",  [o valueForKey:@"uid"], [o valueForKey:@"name"], [o valueForKey:@"first_name"], [o valueForKey:@"sex"], 0, 0, 0];
            
            const char *insert_stmt = [insertSQL UTF8String];
            
            sqlite3_prepare_v2(friendsDB, insert_stmt, -1, &statement, NULL);
            
            if (sqlite3_step(statement) == SQLITE_DONE) {
                //NSLog(@"added: %@", [o valueForKey:@"name"]);
            }
            else {
                NSLog(@"Failed to add: %s", sqlite3_errmsg(friendsDB));
            }
            
            sqlite3_finalize(statement);
        }
        
        sqlite3_close(friendsDB);
    }
    
    for (NSObject <UWFriendDelegate> *o in delegates) {
        
        [o friendsChanged:before!=self.count];
        
        if ([o respondsToSelector:@selector(friendsChanged:)]) {
            
        }
    }
}


- (void)request:(FBRequest *)request didLoadRawResponse:(NSData *)data 
{
    //NSLog(@"Raw response");
}

// End of Facebook

// API

- (void)parseDataForHighscore:(NSData *)data delegate:(id)friendDetailDelegate 
{
    
    //NSLog(@"Highscore: %@", [UWApi parseJson:data]);
    
    sqlite3_stmt *statement;
    
    const char *dbpath = [dbPath UTF8String];
    
    if (sqlite3_open(dbpath, &friendsDB) == SQLITE_OK) {
        
        NSDictionary *friendHighscore = [[(NSDictionary *)[UWApi parseJson:data] objectForKey:@"message"] retain];
        BOOL changed = NO;
        
        NSLog(@"Highscore: %@", friendHighscore);
        
        NSString *insertSQL = [NSString stringWithFormat:@"UPDATE friends SET gameswon = \"%@\", gamehighscore = \"%@\", wordhighscore =  \"%@\" WHERE id = \"%@\"",  
                                   [friendHighscore valueForKey:@"gameswon"], 
                                   [friendHighscore valueForKey:@"gamehighscore"],
                                   [friendHighscore valueForKey:@"wordhighscore"],
                                   [friendHighscore valueForKey:@"user"]];
            
        const char *insert_stmt = [insertSQL UTF8String];
            
        sqlite3_prepare_v2(friendsDB, insert_stmt, -1, &statement, NULL);
            
        if (sqlite3_step(statement) == SQLITE_DONE) {
            //NSLog(@"added: %@", [o valueForKey:@"gameid"]);
            changed = YES;
        }
        else {
            //NSLog(@"Failed to add (Duplicate): %s", sqlite3_errmsg(gamesDB));
        }
        sqlite3_finalize(statement);
        
        sqlite3_close(friendsDB);
        
        [friendHighscore release];
        [friendDetailDelegate updateInfo];
    }
}

// End of API

- (NSInteger)count
{
    sqlite3_stmt *statement;
    
    const char *dbpath = [dbPath UTF8String];
    int _count = 0;
    
    if (sqlite3_open(dbpath, &friendsDB) == SQLITE_OK) {
        
        NSString *selectSQL = [NSString stringWithFormat:@"SELECT COUNT(*) FROM FRIENDS"];
        
        const char *select_stmt = [selectSQL UTF8String];
        
        if (sqlite3_prepare_v2(friendsDB, select_stmt, -1, &statement, NULL) == SQLITE_OK) {
            if (sqlite3_step(statement)) {
                _count = sqlite3_column_int(statement, 0);
            }
        }
        
        sqlite3_finalize(statement);
        sqlite3_close(friendsDB);
    }
    return _count;
}

- (NSInteger)countAtSection:(NSInteger)section
{
    sqlite3_stmt *statement;
    
    NSString *selectSQL = [NSString stringWithFormat:@"SELECT COUNT(*) FROM FRIENDS WHERE UPPER(SUBSTR( name, 1, 1 )) = '%@'", [self getSectionAt:section]];
    
    //NSLog(@"sql: %@", selectSQL);
    
    const char *dbpath = [dbPath UTF8String];
    int _count = 0;
    
    if (sqlite3_open(dbpath, &friendsDB) == SQLITE_OK) {
        
        const char *select_stmt = [selectSQL UTF8String];
        
        if (sqlite3_prepare_v2(friendsDB, select_stmt, -1, &statement, NULL) == SQLITE_OK) {
            if (sqlite3_step(statement)) {
                _count = sqlite3_column_int(statement, 0);
            }
        }
        
        sqlite3_finalize(statement);
        sqlite3_close(friendsDB);
    }
    return _count;
}

- (UWFriend *)getFriendAt:(NSInteger)row
{
    sqlite3_stmt *statement;
    
    const char *dbpath = [dbPath UTF8String];
    UWFriend *friend = [UWFriend alloc];
    
    if (sqlite3_open(dbpath, &friendsDB) == SQLITE_OK) {
        
        NSString *selectSQL = [NSString stringWithFormat:@"SELECT name, id FROM FRIENDS ORDER BY name ASC LIMIT %i, 1", row];
        
        const char *select_stmt = [selectSQL UTF8String];
        
        //            NSLog(@"%@", o);
        
        if (sqlite3_prepare_v2(friendsDB, select_stmt, -1, &statement, NULL) == SQLITE_OK) {
            if (sqlite3_step(statement) == SQLITE_ROW) {
                friend.name = [[NSString alloc] initWithUTF8String:(const char *)sqlite3_column_text(statement, 0)];
                friend.fid = [[NSString alloc] initWithUTF8String:(const char *)sqlite3_column_text(statement, 1)];
            }
        }
        
        sqlite3_finalize(statement);
        sqlite3_close(friendsDB);
    }
    NSLog(@"%@", friend.name);
    return friend;
}

- (UWFriend *)getFriendAt:(NSInteger)row atSection:(NSInteger)section
{
    sqlite3_stmt *statement;
    
    NSString *selectSQL = [NSString stringWithFormat:@"SELECT name, id FROM FRIENDS WHERE UPPER(SUBSTR( name, 1, 1 )) = '%@' ORDER BY name ASC LIMIT %i, 1", [self getSectionAt:section], row];
    
    const char *dbpath = [dbPath UTF8String];
    UWFriend *friend = [UWFriend alloc];
    
    if (sqlite3_open(dbpath, &friendsDB) == SQLITE_OK) {
        
        const char *select_stmt = [selectSQL UTF8String];
        
        if (sqlite3_prepare_v2(friendsDB, select_stmt, -1, &statement, NULL) == SQLITE_OK) {
            if (sqlite3_step(statement) == SQLITE_ROW) {
                friend.name = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 0)];
                friend.fid = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 1)];
            }
        } else {
            NSLog(@"error: %s", sqlite3_errmsg(friendsDB));
        }
        
        sqlite3_finalize(statement);
        sqlite3_close(friendsDB);
    }
    return friend;
}

- (UWFriend *)getFullFriendAt:(NSInteger)row atSection:(NSInteger)section
{
    NSLog(@"getFullFriendAt");
    sqlite3_stmt *statement;
    
    NSString *selectSQL = [NSString stringWithFormat:@"SELECT name, id, gameswon, gamehighscore, wordhighscore FROM FRIENDS WHERE UPPER(SUBSTR( name, 1, 1 )) = '%@' ORDER BY name ASC LIMIT %i, 1", [self getSectionAt:section], row];
    
    const char *dbpath = [dbPath UTF8String];
    UWFriend *friend = [UWFriend alloc];
    
    if (sqlite3_open(dbpath, &friendsDB) == SQLITE_OK) {
        
        const char *select_stmt = [selectSQL UTF8String];
        
        if (sqlite3_prepare_v2(friendsDB, select_stmt, -1, &statement, NULL) == SQLITE_OK) {
            if (sqlite3_step(statement) == SQLITE_ROW) {
                friend.name = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 0)];
                friend.fid = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 1)];
                friend.gameswon = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 2)];
                friend.gamehighscore = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 3)];
                friend.wordhighscore = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 4)];
            }
        } else {
            NSLog(@"error: %s", sqlite3_errmsg(friendsDB));
        }
        
        sqlite3_finalize(statement);
        sqlite3_close(friendsDB);
    }    
    NSLog(@"getFullFriendAt DONE");
    return friend;
}

- (UWFriend *)getFullFriendWithFID:(NSString *)fid
{
    NSLog(@"getFullFriendAt");
    sqlite3_stmt *statement;
    
    NSString *selectSQL = [NSString stringWithFormat:@"SELECT name, id, gameswon, gamehighscore, wordhighscore FROM FRIENDS WHERE id = '%@'   LIMIT 1", fid];
    
    const char *dbpath = [dbPath UTF8String];
    UWFriend *friend = [UWFriend alloc];
    
    if (sqlite3_open(dbpath, &friendsDB) == SQLITE_OK) {
        
        const char *select_stmt = [selectSQL UTF8String];
        
        if (sqlite3_prepare_v2(friendsDB, select_stmt, -1, &statement, NULL) == SQLITE_OK) {
            if (sqlite3_step(statement) == SQLITE_ROW) {
                friend.name = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 0)];
                friend.fid = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 1)];
                friend.gameswon = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 2)];
                friend.gamehighscore = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 3)];
                friend.wordhighscore = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 4)];
            }
        } else {
            NSLog(@"error: %s", sqlite3_errmsg(friendsDB));
        }
        
        sqlite3_finalize(statement);
        sqlite3_close(friendsDB);
    }    
    NSLog(@"getFullFriendAt DONE");
    return friend;
}

- (UWFriend *)getFriend:(NSString *)fid
{
    sqlite3_stmt *statement;
    
    NSString *selectSQL = [NSString stringWithFormat:@"SELECT name, first_name, sex, gameswon, gamehighscore, wordhighscore FROM FRIENDS WHERE id = \"%@\"", fid];
    
    const char *dbpath = [dbPath UTF8String];
    UWFriend *friend = [UWFriend alloc];
    
    if (sqlite3_open(dbpath, &friendsDB) == SQLITE_OK) {
        
        const char *select_stmt = [selectSQL UTF8String];
        
        if (sqlite3_prepare_v2(friendsDB, select_stmt, -1, &statement, NULL) == SQLITE_OK) {
            if (sqlite3_step(statement) == SQLITE_ROW) {
                friend.name = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 0)];
                friend.first_name = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 1)];
                friend.sex = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 2)];
                friend.gameswon = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 3)];
                friend.gamehighscore = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 4)];
                friend.wordhighscore = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 5)];
                friend.fid = fid;
                //NSLog(@"name: %@", friend.first_name);
            }
        } else {
            NSLog(@"error: %s", sqlite3_errmsg(friendsDB));
        }
        
        sqlite3_finalize(statement);
        sqlite3_close(friendsDB);
    }
    return friend;
}

- (void)getHighscoreOfFriend:(NSString *)fid {
    
}

- (NSInteger)sections
{
    sqlite3_stmt *statement;
    
    const char *dbpath = [dbPath UTF8String];
    int _count = 0;
    
    if (sqlite3_open(dbpath, &friendsDB) == SQLITE_OK) {
        
        NSString *selectSQL = [NSString stringWithFormat:@"SELECT COUNT( DISTINCT SUBSTR( name, 1, 1 ) ) FROM FRIENDS"];
        
        const char *select_stmt = [selectSQL UTF8String];
        
        if (sqlite3_prepare_v2(friendsDB, select_stmt, -1, &statement, NULL) == SQLITE_OK) {
            if (sqlite3_step(statement) == SQLITE_ROW) {
                _count = sqlite3_column_int(statement, 0);
            }
        }
        
        sqlite3_finalize(statement);
        sqlite3_close(friendsDB);
    }
    return _count;
}

- (NSString *)getSectionAt:(NSInteger)index
{
    sqlite3_stmt *statement;
    
    const char *dbpath = [dbPath UTF8String];
    NSString *name;
    
    if (sqlite3_open(dbpath, &friendsDB) == SQLITE_OK) {
        
        NSString *selectSQL = [NSString stringWithFormat:@"SELECT DISTINCT UPPER(SUBSTR( name, 1, 1 )) FROM FRIENDS ORDER BY name ASC LIMIT %i, %i", index, index+1];
        
        const char *select_stmt = [selectSQL UTF8String];
        
        //            NSLog(@"%@", o);
        
        if (sqlite3_prepare_v2(friendsDB, select_stmt, -1, &statement, NULL) == SQLITE_OK) {
            if (sqlite3_step(statement) == SQLITE_ROW) {
                name = [[NSString alloc] initWithUTF8String:(const char *)sqlite3_column_text(statement, 0)];
            }
        }
        
        sqlite3_finalize(statement);
        sqlite3_close(friendsDB);
    }
    
    return name;
}

- (NSArray *)getAllSections
{
    sqlite3_stmt *statement;
    
    const char *dbpath = [dbPath UTF8String];
    NSMutableArray *sectionTitles = [[NSMutableArray alloc] init];
    
    if (sqlite3_open(dbpath, &friendsDB) == SQLITE_OK) {
        
        NSString *selectSQL = [NSString stringWithFormat:@"SELECT DISTINCT UPPER(SUBSTR( name, 1, 1 )) FROM FRIENDS ORDER BY name ASC"];
        
        const char *select_stmt = [selectSQL UTF8String];
        
        if (sqlite3_prepare_v2(friendsDB, select_stmt, -1, &statement, NULL) == SQLITE_OK) {
            while (sqlite3_step(statement) == SQLITE_ROW) {
                NSString *sectionName = [[NSString alloc] initWithUTF8String:(const char *)sqlite3_column_text(statement, 0)];
                
                //NSLog(@"%@", sectionName);
                
                [sectionTitles addObject:sectionName];
            }
        }
        
        sqlite3_finalize(statement);
        sqlite3_close(friendsDB);
    }
    
    return [NSArray arrayWithArray:[sectionTitles autorelease]];
}

- (void)clear 
{
    
    const char *dbpath = [dbPath UTF8String];
    
    if (sqlite3_open(dbpath, &friendsDB) == SQLITE_OK) {
        
        NSString *querystring = @"DELETE FROM friends";
        
        const char *query = [querystring UTF8String];
        
        char *errMsg;
        
        if (sqlite3_exec(friendsDB, query, NULL, NULL, &errMsg) != SQLITE_OK) {
            NSLog(@"Failed to truncate friends table: %s", sqlite3_errmsg(friendsDB));
        }
        else {
            NSLog(@"Success truncate friends table");
            [lastUpdated release];
            lastUpdated = nil;
        }
    }
    
    sqlite3_close(friendsDB);
}

- (void)setDelegate:(id)object 
{
    [delegates addObject:object];
}

- (void)unsetDelegate:(id)object
{
    [delegates removeObject:object];
}

- (void)dealloc 
{
    [dbPath dealloc];
//    [friendsDB dealloc];
    [super dealloc];
}

@end
